package com.crm.system.service.impl.permissionManagement;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.entity.sys.UserAccount;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.sys.permissionManagement.SysCompanyPermission;
import com.crm.model.entity.sys.permissionManagement.SysMenuPermission;
import com.crm.model.entity.sys.permissionManagement.SysPermissionGroup;
import com.crm.model.vo.permissionManagement.SysPermissionGroupVO;
import com.crm.service.sys.permissionManagement.SysCompanyPermissionDbService;
import com.crm.service.sys.permissionManagement.SysMenuPermissionDbService;
import com.crm.service.sys.permissionManagement.SysPermissionGroupDbService;
import com.crm.system.service.permissionManagement.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author wll
 * @Date 2020/12/7 16:10
 */
@Service
public class SysPermissionManagementServiceImpl implements SysPermissionManagementService {
    @Autowired
    SysPermissionGroupDbService sysPermissionGroupDbService;

    @Autowired
    SysMenuPermissionService sysMenuPermissionService;

    @Autowired
    SysAccountPermissionService sysAccountPermissionService;

    @Autowired
    SysPermissionGroupService sysPermissionGroupService;

    @Autowired
    SysCompanyPermissionService sysCompanyPermissionService;

    @Autowired
    private SysMenuPermissionDbService sysMenuPermissionDbService;
    @Autowired
    private SysCompanyPermissionDbService sysCompanyPermissionDbService;

    /**
     * 创建权限组
     * @param createPermissionGroupJson
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void insertSysPermissionGroup(String createPermissionGroupJson,String accountId,String permissionGroupId) {
        Map<String,Object> createPermissionGroupMap = createSysPermissionGroupMap(createPermissionGroupJson,accountId,permissionGroupId);
        if(!StringUtils.isBlank(permissionGroupId)){
            //根据权限组ID查询出对应的菜单-权限组关联表主键ID
            List<String> menuPermissionIdList = sysMenuPermissionService.selectMenuPermissionIdList(permissionGroupId);
            if(menuPermissionIdList != null && !menuPermissionIdList.isEmpty()){
                //删除sys_company_permission（公司-权限关联表）
                sysCompanyPermissionService.batchDelSysCompanyPermissionByMPIds(menuPermissionIdList);
            }
            //删除sys_menu_permission（菜单-权限组关联表）
            sysMenuPermissionService.deleteSysMenuPermissionByPGId(permissionGroupId);
            //删除sys_permission_group（权限组表）
            //sysPermissionGroupService.deleteSysPermissionGroupById(permissionGroupId);
        }
        if(createPermissionGroupMap != null && createPermissionGroupMap.size() > 0){
            SysPermissionGroup sysPermissionGroup = (SysPermissionGroup)createPermissionGroupMap.get("sysPermissionGroup");
            if(sysPermissionGroup != null){
                //添加权限组(sys_permission_group)
                if(!StringUtils.isBlank(permissionGroupId)){
                    sysPermissionGroupDbService.updateSysPermissionGroup(sysPermissionGroup);
                } else {
                    sysPermissionGroupDbService.insertSysPermissionGroup(sysPermissionGroup);
                }
            }
            List<SysMenuPermission> sysMenuPermissionList = (List<SysMenuPermission>)createPermissionGroupMap.get("sysMenuPermissionList");
            if(sysMenuPermissionList != null && sysMenuPermissionList.size() > 0){
                //批量添加菜单-权限组关联表(sys_menu_permission)
                sysMenuPermissionDbService.insertSysMenuPermissionBatch(sysMenuPermissionList);
            }
            List<SysCompanyPermission> sysCompanyPermissionList = (List<SysCompanyPermission>)createPermissionGroupMap.get("sysCompanyList");
            if(sysCompanyPermissionList != null && sysCompanyPermissionList.size() > 0){
                //批量添加公司-(菜单-权限组关联表)sys_company_permission
                sysCompanyPermissionDbService.insertSysCompanyPermissionBatch(sysCompanyPermissionList);
            }
        }
    }

    /**
     * 创建权限组实体类封装
     * @param createPermissionGroupJson
     * @return
     */
    public Map<String,Object> createSysPermissionGroupMap(String createPermissionGroupJson,String accountId,String permissionGroupId){
        Map<String,Object> createPermissionGroupMap = new HashMap<>();
        List<SysMenuPermission> sysMenuPermissionList = new LinkedList<>();
        List<SysCompanyPermission> sysCompanyPermissionList = new LinkedList<>();
        if(!StringUtils.isBlank(createPermissionGroupJson)){
            //创建权限组JSON信息
            JSONObject jsonObject = JSONObject.parseObject(createPermissionGroupJson);

            if(StringUtils.isBlank(permissionGroupId)){
                /** 权限组信息*/
                SysPermissionGroup sysPermissionGroup = new SysPermissionGroup();
                JSONObject permissionGroupMsg = jsonObject.getJSONObject("permissionGroupMsg");
                permissionGroupId = CommonUtils.getGUID();
                sysPermissionGroup.setPermissionGroupId(permissionGroupId);//权限组ID
                sysPermissionGroup.setPermissionGroupName(permissionGroupMsg.getString("permissionGroupName"));//权限组名
                sysPermissionGroup.setRemark(permissionGroupMsg.getString("remark"));//备注
                sysPermissionGroup.setSysId(permissionGroupMsg.getString("sysId"));//系统ID
                sysPermissionGroup.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());//删除状态
                sysPermissionGroup.setCreatePeopleId(accountId);//创建人
                sysPermissionGroup.setCreateTm(new Date());//创建时间
                createPermissionGroupMap.put("sysPermissionGroup",sysPermissionGroup);
            } else {
                SysPermissionGroup sysPermissionGroup = sysPermissionGroupDbService.selectSysPermissionGroupById(permissionGroupId);
                JSONObject permissionGroupMsg = jsonObject.getJSONObject("permissionGroupMsg");
                sysPermissionGroup.setPermissionGroupName(permissionGroupMsg.getString("permissionGroupName"));//权限组名
                sysPermissionGroup.setRemark(permissionGroupMsg.getString("remark"));//备注
                sysPermissionGroup.setUpdatePeopleId(accountId);//更新人ID
                sysPermissionGroup.setUpdateTm(new Date());//更新时间
                createPermissionGroupMap.put("sysPermissionGroup",sysPermissionGroup);
            }

            //菜单与权限组集合
            List<JSONObject> menuList = new ArrayList<>();
            //公司与菜单-权限组关联表集合
            List<JSONObject> companyList = new ArrayList<>();

            List<JSONObject> list = new ArrayList<JSONObject>();
            JSONArray selectCheckedNodesArray = jsonObject.getJSONArray("selectCheckedNodesArray");//选中节点列表

            for(int index = 0;index < selectCheckedNodesArray.size();index++){
                JSONObject tmpSelectCheckedNodesJson = selectCheckedNodesArray.getJSONObject(index);
                tmpSelectCheckedNodesJson.put("permissionGroupId",permissionGroupId);
                list.add(tmpSelectCheckedNodesJson);
            }


            Map<String,List<JSONObject>> map = list.stream().collect(Collectors.groupingBy(tmpJson -> tmpJson.getString("groupId")));
            for(String key : map.keySet()){
                int permissionRange = 0;
                List<JSONObject> tmpJsonList = map.get(key);
                for(int index = 0;index < tmpJsonList.size();index++){
                    JSONObject treeLevelJson =  tmpJsonList.get(index);
                    String menuType = treeLevelJson.getString("menuType");
                    if("0".equals(menuType)){
                        permissionRange = 2;//(权限范围--0:个人数据; 1:地区数据；2:全部数据)
                        treeLevelJson.put("menuPermissionId",CommonUtils.getGUID());
                        menuList.add(treeLevelJson);
                    }else if("2".equals(menuType)){
                        int isCheckAll = treeLevelJson.getInteger("isCheckAll");
                        if(isCheckAll == 1){
                            permissionRange = 1;
                        }else if(isCheckAll == 2){
                            permissionRange = 2;
                        }else{
                            permissionRange = 0;
                        }
                        break;
                    }
                }

                for(int index = 0;index < tmpJsonList.size();index++) {
                    JSONObject tmpJson =  tmpJsonList.get(index);
                    tmpJson.put("permissionRange",permissionRange);
                }
            }

            for(String key :map.keySet()){
                List<JSONObject> tmpJsonList = map.get(key);
                for(int index = 0;index < tmpJsonList.size();index++){
                    JSONObject menuCompanyJSON =  tmpJsonList.get(index);
                    String menuType = menuCompanyJSON.getString("menuType");
                    if("1".equals(menuType)){
                        menuCompanyJSON.put("menuPermissionId",CommonUtils.getGUID());
                        menuList.add(menuCompanyJSON);
                    }else if("4".equals(menuType) &&  1 == menuCompanyJSON.getInteger("permissionRange")){
                        companyList.add(menuCompanyJSON);
                    }
                }
            }

            for(JSONObject menuJSONObject:menuList){
                for(int index = 0; index < companyList.size(); index++){
                    JSONObject companyJSONObject =  companyList.get(index);
                    if(menuJSONObject.getString("groupId").equals(companyJSONObject.getString("groupId"))){
                        companyJSONObject.put("menuPermissionId",menuJSONObject.getString("menuPermissionId"));
                    }
                }
            }

            for(JSONObject menuJSON: menuList){
                SysMenuPermission sysMenuPermission = new SysMenuPermission();
                sysMenuPermission.setMenuPermissionId(menuJSON.getString("menuPermissionId"));//主键
                sysMenuPermission.setMenuId(menuJSON.getString("nodeId"));//菜单ID
                sysMenuPermission.setPermissionGroupId(menuJSON.getString("permissionGroupId"));//权限组ID
                sysMenuPermission.setPermissionRange(menuJSON.getInteger("permissionRange").shortValue());//权限范围--0:个人数据; 1:地区数据；2:全部数据
                sysMenuPermission.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());//删除状态--0:正常;1:已删除
                sysMenuPermission.setCreateTm(new Date());//创建时间
                sysMenuPermission.setCreatePeopleId(accountId);
                sysMenuPermissionList.add(sysMenuPermission);
            }
            createPermissionGroupMap.put("sysMenuPermissionList",sysMenuPermissionList);

            for(JSONObject companyJSON: companyList){
                SysCompanyPermission sysCompanyPermission = new SysCompanyPermission();
                sysCompanyPermission.setCompanyPermissionId(CommonUtils.getGUID());//主键
                sysCompanyPermission.setCompanyId(companyJSON.getString("nodeId"));//公司ID
                sysCompanyPermission.setMenuPermissionId(companyJSON.getString("menuPermissionId"));//菜单-权限组关联表主键
                sysCompanyPermission.setCreateTm(new Date());//创建时间
                sysCompanyPermission.setCreatePeopleId(accountId);
                sysCompanyPermissionList.add(sysCompanyPermission);
            }
            createPermissionGroupMap.put("sysCompanyList",sysCompanyPermissionList);
        }
        return createPermissionGroupMap;
    }

    //根据条件分页查询权限组名单列表
    @Override
    public DhPageInfo<SysPermissionGroupVO> getPermissionManagementList(Integer pageIndex, Integer pageSize, String searchInfo) {
        UserAccount account = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<SysPermissionGroup> permissionGroups = sysPermissionGroupDbService.selectPermissionManagementInfo(searchInfo);
        PageInfo<SysPermissionGroup> pageInfo = new PageInfo<>(permissionGroups);
        List<SysPermissionGroupVO> result = new ArrayList<SysPermissionGroupVO>();
        for (SysPermissionGroup dbItem : pageInfo.getList()) {
            SysPermissionGroupVO sysPermissionGroupVO = new SysPermissionGroupVO(dbItem);
            boolean isAdmin = CommonUtils.isAdmin(account.getUserId());
            if(isAdmin){
                sysPermissionGroupVO.setIsAdmin("0");
            }
            result.add(sysPermissionGroupVO);
        }
        return new DhPageInfo<SysPermissionGroupVO>(pageInfo, result);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void delPermissionGroup(String permissionGroupId) {
        //根据权限组ID查询出对应的菜单-权限组关联表主键ID
        List<String> menuPermissionIdList = sysMenuPermissionService.selectMenuPermissionIdList(permissionGroupId);

        if(menuPermissionIdList != null && !menuPermissionIdList.isEmpty()){
            //删除sys_company_permission（公司-权限关联表）
            sysCompanyPermissionService.batchDelSysCompanyPermissionByMPIds(menuPermissionIdList);
        }
        //删除sys_menu_permission（菜单-权限组关联表）
        sysMenuPermissionService.deleteSysMenuPermissionByPGId(permissionGroupId);
        //删除sys_account_permission（账号-权限组关联表）
        sysAccountPermissionService.deleteSysAccountPermissionByPGId(permissionGroupId, null);
        //删除sys_permission_group（权限组表）
        sysPermissionGroupService.deleteSysPermissionGroupById(permissionGroupId);
    }
}
